import axios from 'axios'
import vueApp from '../main.js'
const baseUrl = 'http://chunfengai.top:28081'
axios.interceptors.response.use(
  (res) => {
    return res
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
        //登录
        case 500:
          vueApp.$message({
            message: '服务器繁忙，请稍后再试',
            type: 'error',
          })
      }
    }
    return Promise.reject(error)
  }
)
axios.defaults.timeout = 60000
const request = (params) => {
  /**
   * @params method url params(get)/data(post)
   */
  // axios.defaults.headers.common['Authorization'] =
  //   'Bearer ' + localStorage.getItem('token')
  axios.defaults.headers.common['Authorization'] =
    'Bearer ' + localStorage.getItem('token')
  return new Promise((resolve, reject) => {
    params.url = baseUrl + params.url
    axios(params)
      .then((res) => {
        // console.log('request res :>> ', res)
        if (res.data.code == 200) {
          resolve(res)
        } else if (res.data.code == 401) {
          // vueApp.$showLogin()
          reject(401)
        } else {
          vueApp.$message(res.data.msg)
        }
      })
      .catch((err) => {
        console.log('request err :>> ', err)
        if (err.code == 'ECONNABORTED') {
          vueApp.$message('服务器繁忙，请稍后再试')
          reject('ECONNABORTED')
        } else {
          vueApp.$message(err.message)
        }
      })
  })
}

export default request
